package com.renchunlin.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.renchunlin.myapplication.base.BaseActivity;
import com.renchunlin.myapplication.utils.OkHttpUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.engine.impl.PicassoEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class MainActivity extends BaseActivity {

    /*储存权限*/
    private String[] mStrPermission =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private static final int REQUEST_CODE_CHOOSE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView() {
        Button mButton = findViewById(R.id.mButton);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPermission();
            }
        });
    }

    /*授予权限*/
    private void getPermission() {
        requestPermission(mStrPermission, 2);
    }

    /* 权限成功回调函数*/
    @Override
    public void permissinSucceed(int code) {
        super.permissinSucceed(code);
        switch (code) {
            case 2:
                //打开相册
                initOpen();
                break;
        }
    }

    private void initOpen() {
        Matisse
                .from(MainActivity.this)
                //选择图片
                .choose(MimeType.ofImage())
                //是否只显示选择的类型的缩略图，就不会把所有图片视频都放在一起，而是需要什么展示什么
                .showSingleMediaType(true)
                //这两行要连用 是否在选择图片中展示照相 和适配安卓7.0 FileProvider
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "PhotoPicker"))
                //有序选择图片 123456...
                .countable(true)
                //最大选择数量为9
                .maxSelectable(9)
                //选择方向
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                //界面中缩略图的质量
                .thumbnailScale(0.8f)
                //蓝色主题
                .theme(R.style.Matisse_Zhihu)
                //黑色主题
                .theme(R.style.Matisse_Dracula)
                //Glide加载方式
                .imageEngine(new GlideEngine())
                //Picasso加载方式
                .imageEngine(new PicassoEngine())
                //请求码
                .forResult(REQUEST_CODE_CHOOSE);
    }

    /* 权限失败回调函数*/
    @Override
    public void permissionFailing(int code) {
        super.permissionFailing(code);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            List<Uri> pathList = Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + pathList);

            Uri uri = null;
            for (int i = 0; i < pathList.size(); i++) {
                uri = pathList.get(i);
            }

            String dataUrl=getPath(MainActivity.this, uri);
            Log.d("Matisse", "dataUrl: " + dataUrl);
            initUpload(dataUrl);
        }
    }

    private void initUpload(String file) {

        OkHttpUtils.post_file(MainActivity.this, "http://192.168.1.3:3000/upload", file, new OkHttpUtils.OnOkHttpCallback() {
            @Override
            public void onFailure(IOException e) {

            }

            @Override
            public void onFailure(String msg) {

            }

            @Override
            public void onSuccessful(String json) {

            }
        });
    }

    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {"_data"};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }
}
